import 'package:enterprise_v6_app/app/core/ext/ext.dart';
import 'package:enterprise_v6_app/app/core/values/gaps.dart';
import 'package:flutter/material.dart';

///自定义多选复选框(模块化)---任意数量----唯一
/// [choicesText] 多个复选框集合
/// [initialChoices]多个复选框集合初始值
/// [onChoiceChanged] 选中后的回调   index复选框的角标    value true选中  false未选中
/// [checkboxBuilder] 模块化-在外面构建(自定义)复选框 isSelected设置是否选中  onChanged  CustomCheckbox（任何widget）的点击回调=》_onChoiceChanged
class CustomMultiChoiceCheckbox extends StatefulWidget {
  const CustomMultiChoiceCheckbox({
    required this.choicesText,
    required this.initialChoices,
    required this.onChoiceChanged,
    required this.checkboxBuilder,
    super.key,
  }) : assert(choicesText.length == initialChoices.length);
  final List<String> choicesText;
  final List<bool> initialChoices;

  // final ValueChanged<int,bool> onChoiceChanged;
  final void Function(int int, bool bool) onChoiceChanged;
  final Widget Function(bool isSelected, VoidCallback onChanged) checkboxBuilder;

  @override
  CustomMultiChoiceCheckboxState createState() => CustomMultiChoiceCheckboxState();
}

class CustomMultiChoiceCheckboxState extends State<CustomMultiChoiceCheckbox> {
  late List<bool> _selectedChoices;

  @override
  void initState() {
    super.initState();
    _selectedChoices = List.from(widget.initialChoices);
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: List<Widget>.generate(widget.choicesText.length, (index) {
        return _buildChoiceCheckbox(_selectedChoices[index], widget.choicesText[index], index);
      }),
    );
  }

  Widget _buildChoiceCheckbox(bool isSelected, String text, int index) {
    return Row(
      children: [
        widget.checkboxBuilder(isSelected, () => _onChoiceChanged(index)),
        AppGaps.hGap4,
        Text(text),
        AppGaps.hGap20,
      ],
    ).clickOnce(() {
      _onChoiceChanged(index);
    });
  }

  void _onChoiceChanged(int index) {
    setState(() {
      // 更新被选中的复选框的状态，其余设置为未选中
      for (int i = 0; i < _selectedChoices.length; i++) {
        _selectedChoices[i] = i == index ? !_selectedChoices[i] : false;
      }
    });
    widget.onChoiceChanged(index, _selectedChoices[index]);
  }
}
